package com.star.uc.infras.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.star.common.core.contract.constant.ContextConstants;
import com.star.common.core.contract.enums.ResultCodeEnum;
import com.star.common.core.contract.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * 拦截token，并校验token
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/10/18 15:51
 */
@Component
public class SaTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(ContextConstants.AUTHORIZATION);
        //获取当前登录者的 token 剩余有效时间 (单位: 秒)
        StpUtil.getTokenTimeout();
        //未登录token
        if (StringUtils.isBlank(token)
                // token 过期
                || Objects.isNull(StpUtil.getTokenInfo())
                || StringUtils.isBlank(StpUtil.getTokenInfo().getTokenValue())
                // token 不匹配
                || !token.equalsIgnoreCase(StpUtil.getTokenInfo().getTokenValue())) {
            // 登录验证未通过，进行拦截处理
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new ServiceException(ResultCodeEnum.USER_NOT_LOGIN_OR_EXPIRE);
        }
        // 登录不是活跃会话，相当于登录失效，同账号被挤。
        if (!StpUtil.isLogin()) {
            throw new ServiceException(ResultCodeEnum.LOG_OUT);
        }
        return true;
    }
}
